from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.permissions import PermissionSerializer, ContentTypeSerializer, GroupSerializer, \
    PermissionSimpleSerializer, AdminSerializer, GroupSimpleSerializer

# 定制权限数据的视图集
from users.models import User


class PermissionViewSet(ModelViewSet):
    # 1 管理员权限
    permission_classes = [IsAdminUser]
    # 2 指定序列化类
    serializer_class = PermissionSerializer
    # 3 设定数据查询集
    queryset = Permission.objects.all()

    # 定制权限类型获取的方法
    def content_types(self, request):
        # 1 获取数据集
        content_type = ContentType.objects.all()
        # 2 数据集的序列化
        serializer = ContentTypeSerializer(instance=content_type, many=True)
        # 3 返回数据
        return Response(serializer.data)

# 定制用户组数据的视图集
class GroupViewSet(ModelViewSet):
    # 1 管理员权限
    permission_classes = [IsAdminUser]
    # 2 指定序列化类
    serializer_class = GroupSerializer
    # 3 设定数据查询集
    queryset = Group.objects.all()

    # 定制权限获取的方法
    def simple(self, request):
        # 1 获取数据集
        permission_data = Permission.objects.all()
        # 2 数据集的序列化
        serializer = PermissionSimpleSerializer(instance=permission_data, many=True)
        # 3 返回数据
        return Response(serializer.data)

# 定制用户组数据的视图集
class AdminViewSet(ModelViewSet):
    # 1 管理员权限
    permission_classes = [IsAdminUser]
    # 2 指定序列化类
    serializer_class = AdminSerializer
    # 3 设定数据查询集
    queryset = User.objects.filter(is_staff=True)
    # 4 动态路由的正则匹配规则
    lookup_url_regex = '\d+'
    # 定制权限获取的方法
    def simple(self, request):
        # 1 获取数据集
        group_data = Group.objects.all()
        # 2 数据集的序列化
        serializer = GroupSimpleSerializer(instance=group_data, many=True)
        # 3 返回数据
        return Response(serializer.data)
